package com.meshnetics.gb.type.impl;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Utility class providing some static algorithms to check and work with bytebuffer
 *
 * @author AKovylin
 */
public class ByteUtils {
    private ByteUtils() {
    }

    public static void ensureNotNull(ByteBuffer bb) {
        if (bb == null) {
            throw new NullPointerException("bb is null");
        }
    }

    public static void ensureCapacity(ByteBuffer bb, int requiredBytes) {
        ensureCapacity(bb, requiredBytes, requiredBytes);
    }

    public static void ensureCapacity(ByteBuffer bb, int requiredBytes, int exceptionRequiredBytes) {
        if (bb.remaining() < requiredBytes) {
            throw new IllegalArgumentException("not enough bytes left in ByteBuffer, atleast " +
                    exceptionRequiredBytes + " required");
        }
    }

    public static void fillFromLong(long l, byte[] bytes, int offset, int count) {
        for (int i = offset + count - 1; i >= offset; i--) {
            bytes[i] = (byte) (l & 0xff);
            l = l >> 8;
        }
    }

    public static void readFromByteBuffer(ByteBuffer bb, byte[] bytes) {
        // todo better to rotate array after reading
        if (bytes.length > 1 && bb.order() == ByteOrder.LITTLE_ENDIAN) {
            for (int i = bytes.length - 1; i >= 0; i--) {
                bytes[i] = bb.get();
            }
        } else {
            bb.get(bytes);
        }
    }

    public static void writeToByteBuffer(ByteBuffer bb, byte[] bytes) {
        // todo better to rotate array after reading
        if (bytes.length > 1 && bb.order() == ByteOrder.LITTLE_ENDIAN) {
            for (int i = bytes.length - 1; i >= 0; i--) {
                bb.put(bytes[i]);
            }
        } else {
            bb.put(bytes);
        }
    }
}
